package cn.chengpengper.rpc.proxy.bytebuddy;

import cn.chengpengper.rpc.proxy.api.BaseProxyFactory;
import cn.chengpengper.rpc.proxy.api.ProxyFactory;
import cn.chengpengper.rpc.spi.annotation.SpiClass;
import lombok.extern.slf4j.Slf4j;
import net.bytebuddy.ByteBuddy;
import net.bytebuddy.implementation.InvocationHandlerAdapter;

/**
 * @author chengpeng.hu
 */
@Slf4j
@SpiClass
public class ByteBuddyProxyFactory<T> extends BaseProxyFactory<T> implements ProxyFactory {
    @Override
    public <T> T getProxy(Class<T> clazz) {
        log.info("基于ByteBuddy动态代理机制");
        try {
            return (T) new ByteBuddy().subclass(Object.class)
                    .implement(clazz)
                    .intercept(InvocationHandlerAdapter.of(objectProxy))
                    .make()
                    .load(ByteBuddyProxyFactory.class.getClassLoader())
                    .getLoaded()
                    .getDeclaredConstructor()
                    .newInstance();
        } catch (Exception e) {
            log.error("ByteBuddy proxy throws exception:", e);
        }
        return null;

    }
}
